package com.cyms.modules.order.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.cyms.common.annotation.SysLog;
import com.cyms.modules.sys.controller.AbstractController;
import com.cyms.modules.sys.entity.SysUserEntity;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cyms.modules.order.entity.OrderCarAmountEntity;
import com.cyms.modules.order.entity.OrderCarEntity;
import com.cyms.modules.order.entity.OrderCarPayEntity;
import com.cyms.modules.order.entity.OrderEntity;
import com.cyms.modules.order.service.OrderAmountService;
import com.cyms.modules.order.service.OrderCarAmountService;
import com.cyms.modules.order.service.OrderCarPayService;
import com.cyms.modules.order.service.OrderCarService;
import com.cyms.modules.order.service.OrderService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cyms.common.utils.DateUtils;
import com.cyms.common.utils.PageUtils;
import com.cyms.common.utils.R;

/**
 * 车辆派遣
 *
 * @author low
 * @email tolower@foxmail.com
 * @date 2018-12-19 00:49:45
 */
@RestController
@RequestMapping("order/ordercar")
public class OrderCarController extends AbstractController {
	@Autowired
	private OrderCarService orderCarService;
	@Autowired
	private OrderCarAmountService orderCarAmountService;
	@Autowired
	private OrderCarPayService orderCarPayService;
	@Autowired
	private OrderService orderService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("order:ordercar:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = orderCarService.queryPage(params);

		return R.ok().put("page", page);
	}
	/**
	 * 应收车费列表
	 */
	@RequestMapping("/amountQuery")
	public R amountQuery(@RequestParam Map<String, Object> params) {
		params.put("createOrg",getUser().getCompanyId());
		List list = orderCarService.queryAmountQueryPage(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 应付车费列表
	 */
	@RequestMapping("/payQuery")
	public R payQuery(@RequestParam Map<String, Object> params) {
		params.put("createOrg",getUser().getCompanyId());
		List list = orderCarService.queryPayQueryPage(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 单车核算查询列表
	 */
	@RequestMapping("/carCostQuery")
	public R carCostQuery(@RequestParam Map<String, Object> params) {
		params.put("createOrg",getUser().getCompanyId());
		List list = orderCarService.queryCarCostQueryPage(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 单车核算订单详情列表
	 */
	@RequestMapping("/carCostDetail")
	public R carCostDetail(@RequestParam Map<String, Object> params) {
		List list = orderCarService.queryCarCostDetail(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 单车应收订单详情列表
	 */
	@RequestMapping("/carAmountDetail")
	public R carAmountDetail(@RequestParam Map<String, Object> params) {
		List list = orderCarService.queryCarCostDetail(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 单车应付订单详情列表
	 */
	@RequestMapping("/carPayDetail")
	public R carPayDetail(@RequestParam Map<String, Object> params) {
		List list = orderCarService.queryCarCostDetail(params);

		return R.ok().put("list", list);
	}
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("order:ordercar:info")
	public R info(@PathVariable("id") Long id) {
		OrderCarEntity orderCar = orderCarService.selectById(id);
		List<OrderCarAmountEntity> carAmountList = orderCarAmountService
				.selectList(new EntityWrapper<OrderCarAmountEntity>().eq("order_car_id", id));
		orderCar.setCarAmountList(carAmountList);
		//
		List<OrderCarPayEntity> carPayList = orderCarPayService
				.selectList(new EntityWrapper<OrderCarPayEntity>().eq("order_car_id", id)
				.orderBy("pay_date", true));
		orderCar.setCarPayList(carPayList);
		return R.ok().put("orderCar", orderCar);
	}

	/**
	 * 保存
	 */
	@SysLog("新增派遣车辆")
	@RequestMapping("/save")
	@RequiresPermissions("order:ordercar:save")
	public R save(@RequestBody OrderCarEntity orderCar) {
		orderCar.setCreateDate(new Date());
		orderCar.setStatus("1");
		orderCar.setTotalPay(
				orderCar.getCarAmountList().parallelStream().map(x -> x.getAmount()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.valueOf(0)));
		orderCar.setAlreadyPay(
				orderCar.getCarPayList().parallelStream().map(x -> x.getPayAmount()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.valueOf(0)));
		orderCarService.insert(orderCar);
		//
		//
		orderCar.getCarPayList().parallelStream().forEach(carPay -> {
			carPay.setOrderCarId(orderCar.getId());
			orderCarPayService.insert(carPay);
		});
		orderCar.getCarAmountList().parallelStream().forEach(carAmount -> {
			carAmount.setOrderCarId(orderCar.getId());
			orderCarAmountService.insert(carAmount);
		});
		//
		OrderEntity order = orderService.selectById(orderCar.getOrderId());
		order.setStatus("3");
		orderService.updateById(order);
		return R.ok();
	}

	/**
	 * 修改
	 */
	@SysLog("修改派遣车辆")
	@RequestMapping("/update")
	@RequiresPermissions("order:ordercar:update")
	public R update(@RequestBody OrderCarEntity orderCar) {
		if (orderCar.getCarAmountList().size() > 0) {
			orderCarAmountService.deleteBatchIds(
				orderCar.getCarAmountList().parallelStream().map(x -> x.getId()).collect(Collectors.toList()));
		}
		orderCar.getCarAmountList().parallelStream().forEach(carAmount -> {
			carAmount.setOrderCarId(orderCar.getId());
			orderCarAmountService.insert(carAmount);
		});
		orderCar.setTotalPay(
				orderCar.getCarAmountList().parallelStream().map(x -> x.getAmount()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.valueOf(0)));
		//
		if (orderCar.getCarPayList().size() > 0) {
			orderCarPayService.deleteBatchIds(
				orderCar.getCarPayList().parallelStream().map(x -> x.getId()).collect(Collectors.toList()));
		}
		orderCar.getCarPayList().parallelStream().forEach(carPay -> {
			carPay.setOrderCarId(orderCar.getId());
			orderCarPayService.insert(carPay);
		});
		orderCar.setAlreadyPay(
				orderCar.getCarPayList().parallelStream().map(x -> x.getPayAmount()).reduce((x, y) -> x.add(y)).orElse(BigDecimal.valueOf(0)));
		orderCarService.updateById(orderCar);
		return R.ok();
	}
	@SysLog("修改派遣车辆")
    @RequestMapping({"/finishOrderCar"})
    @RequiresPermissions({"order:ordercar:update"})
    public R finishOrderCar(@RequestBody OrderCarEntity orderCar) {
        if (orderCar.getCarPayList().size() > 0) {
        	orderCarPayService.deleteBatchIds(
    				orderCar.getCarPayList().parallelStream().map(x -> x.getId()).collect(Collectors.toList()));
        }

        orderCar.getCarPayList().parallelStream().forEach((carPay) -> {
            carPay.setOrderCarId(orderCar.getId());
            this.orderCarPayService.insert(carPay);
        });
        orderCar.setAlreadyPay((BigDecimal)orderCar.getCarPayList().parallelStream().map((x) -> {
            return x.getPayAmount();
        }).reduce((x, y) -> {
            return x.add(y);
        }).orElse(BigDecimal.valueOf(0L)));
        this.orderCarService.updateById(orderCar);
        return R.ok();
    }
	/**
	 * 修改
	 */
	@SysLog("订单批量销账")
	@RequestMapping("/batchFinishOrder")
	@RequiresPermissions("order:ordercar:update")
	public R batchFinishOrder(@RequestParam Map<String,Object> params) {
		
		SysUserEntity user = getUser();
		String codes=(String) params.get("codes");
		Date sDate = DateUtils.stringToDate((String)params.get("startDate"), "yyyy-MM-dd");
		Date eDate = DateUtils.stringToDate((String)params.get("endDate"), "yyyy-MM-dd");
		orderCarService.batchFinishOrder(user,codes.split(","),sDate,eDate);

		return R.ok();
	}
	/**
	 * 删除
	 */
	@SysLog("删除派遣车辆")
	@RequestMapping("/delete")
	@RequiresPermissions("order:ordercar:delete")
	public R delete(@RequestBody Long[] ids) {
		orderCarService.deleteBatchIds(Arrays.asList(ids));

		return R.ok();
	}

}
